<template>
	<view class="content" :style="{marginTop:`-${heightKeyboard}px`}">
		<scroll-view class="scroll" :scroll-top="scrollTop" scroll-y="true" :scroll-with-animation="true"
			:refresher-enabled="true" :refresher-triggered="triggered" :refresher-threshold="100"
			refresher-background="#F9F6F6" @refresherrefresh="onRefresh">
			<view v-for="(item,index) in chatList">
				<view v-if="item.duration>60000" class="show-time">
					{{chatTime(item.time)}}
				</view>
				<chatItem :payload="item" :systemHeightWidth="systemHeightWidth" @openVideoImgPop="openVideoImgPop">
				</chatItem>
			</view>
		</scroll-view>
		<view class="send">
			<view class="send-content">
				<image @click="popupRef.open()"
					src="https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-61.png" mode=""></image>
				<input class="text-input" cursor-spacing='200' :maxlength="1000" @focus="handleFocue" @blur="handleBlur"
					@confirm="send" v-model="text" type="text" :adjust-position="false" placeholder="沟通一下..." />
				<view @click="send" class="xjs-btn-primary btn" size="mini" type="primary">发送</view>
			</view>
		</view>
	</view>
	<uni-popup ref="popupRef" type="bottom" background-color="#fff">
		<view class="pop">
			<view @click="choose('img')" class="line">图片</view>
			<view @click="choose('video')" class="line">视频</view>
			<view @click="popupRef.close()" class="xjs-btn-primary">取消</view>
		</view>
	</uni-popup>
	<uni-popup ref="popupVideoImgRef" type="center" background-color="#fff" @change="changePop">
		<view class="videoImgPop">
			<template v-if="videoImgUrl.type=='img'">
				<view class="image-content" :style="{alignItems: `${videoImgUrl.imgIsCenter?'center':'start'}`}">
					<image :src="videoImgUrl.url" mode="widthFix"></image>
				</view>
			</template>
			<template v-if="videoImgUrl.type=='video'">
				<video v-if="autoplay" :src="videoImgUrl.url" :autoplay="autoplay" object-fit="contain"></video>
			</template>
			<uni-icons @click="popupVideoImgRef.close()" class="close" type="closeempty" size="35"
				color="#fff"></uni-icons>
		</view>
	</uni-popup>
</template>

<script setup lang="ts">
	import { ImServerClass } from '@/hooks/useIm/index'
	import { onLoad,onShow, onPullDownRefresh } from '@dcloudio/uni-app'
	import { chatTime } from '@/hooks/useDay'
	import { useImStoreToRefs } from '@/store/useImStore'
	const { imServer } = useImStoreToRefs()
	import { useUserStoreToRefs } from '@/store/useUserStore'
	const { userfromInfo,userInfo } = useUserStoreToRefs()
	import { ref, reactive, nextTick } from 'vue';
	import api from '@/api'
	const conversationId = ref("") //当前聊天对象id
	const scrollTop = ref(10000)
	const triggered = ref(false)
	const chatList = ref([])
	const text = ref("")
	const popupRef = ref()

	const systemHeightWidth = ref({
		height: 0,
		width: 0
	})
	const isToLogin = ref(false) //只有从登录页面回来时在需要执行获取历史记录
	onShow( async ()=>{
		if (!userInfo.value) {
			uni.navigateTo({
				url: '/pages/login/index'
			})
			isToLogin.value = true
			return
		}
		if(isToLogin.value){
			await getChatList()
			toDown(500)
		}
	})
	onLoad(async (query) => {
		console.log(query,"queryquery")
		isToLogin.value = false
		if(query.id == 'undefined'){
			uni.showToast({
				title:'用户信息有误',
				duration:3000,
				mask:true
			})
			uni.navigateBack()
			return
		}
		uni.getSystemInfo({
			success: (res) => {
				systemHeightWidth.value.height = res.windowHeight
				systemHeightWidth.value.width = res.windowWidth
			}
		});
		uni.setNavigationBarTitle({
			title: query.username
		});
		userfromInfo.value = {
			username: query.username,
			avatar: query.avatar,
			id: query.id  //会话列表出取值conversationId，首页进入时直接取值id即可
		}
		conversationId.value = "xjs_" + userfromInfo.value.id
		if (!userInfo.value) {
			return
		}
		await getChatList()
		toDown(500)
		imServer.value.readMsg(conversationId.value)
		uni.$on("onChatContent", (data) => {
			if (conversationId.value == data.data.from) {
				imServer.value.readMsg(conversationId.value)
				chatList.value.push(data.data)
				toDown(500)
			}
		})
		// imServer.value.getPresenceStatus((e)=>{
		// 	console.log('在线状态',e)
		// },[conversationId.value])
	})
	const videoImgUrl = ref<any>({})
	const autoplay = ref(false)
	const popupVideoImgRef = ref()
	const openVideoImgPop = (item) => {
		videoImgUrl.value = item
		popupVideoImgRef.value.open()
	}
	const changePop = (e) => {
		setTimeout(() => {
			autoplay.value = e.show
		}, 300)
	}
	const onRefresh = async () => {
		if (triggered.value) {
			return
		}
		triggered.value = true
		if (chatList.value.length > 0) {
			await getChatList()
		}
		setTimeout(() => {
			triggered.value = false
		}, 1000)
	}

	const getChatList = () => {
		console.log("历史记录")
		return new Promise((resolve) => {
			imServer.value.getHistoryMessages((data) => {
				if (data.messages.length > 0) {
					let lastTime = chatList.value.length == 0 ? new Date().getTime() : chatList.value[0].time
					let reverseData = data.messages.reverse()
					reverseData.forEach((item, index) => {
						let ltime = reverseData[index + 1] ? reverseData[index + 1].time : lastTime
						let ttime = reverseData[index].time
						reverseData[index].duration = ltime - ttime
					})
					chatList.value = [...reverseData, ...chatList.value]

					console.log("成功获取历史消息", chatList.value);
				} else {

				}

				resolve(true)
			}, {
				targetId: conversationId.value,
				chatType: "singleChat",
				cursor: chatList.value.length > 0 ? chatList.value[0].id : ""
			},(err)=>{
				console.log(err,'聊天页,通过外部路径（订阅）直接进入如果没有初始化，则先初始化登录在重新调用聊天记录')
				if(err.type==700){
					imServer.value = new ImServerClass()
					imServer.value.login().then(async(success) => {
						if (success) {
							chatList.value = []
							await getChatList()
							toDown(500)
						}
					})
				}
			})
		})
	}
	const toDown = (duration = 1000) => {
		setTimeout(() => {
			scrollTop.value += 1000
		}, duration)
	}
	//设置键盘弹起时的高度
	const heightKeyboard = ref(0)
	//聚焦时触发
	const handleFocue = (e) => {
		console.log('handleFocue', e)
		heightKeyboard.value = e.detail.height
		toDown(400)

	}
	//失去焦点
	const handleBlur = (e) => {
		console.log('handleBlur', e)
		heightKeyboard.value = 0
	}
	const send = () => {
		if (text.value.trim().length <= 0) {
			uni.showToast({
				mask: true,
				icon: 'none',
				title: "请输入消息"
			})
			return
		}
		imServer.value.sendText((res) => {
			chatList.value.push(res.message)
			sendMessagePush(res.message.msg)
			text.value = ''
			toDown(500)
		}, {
			to: conversationId.value,
			msg: text.value
		})
	}
	const choose = (type) => {
		switch (type) {
			case 'img':
				imServer.value.sendImage((res) => {
					popupRef.value.close()
					chatList.value.push(res.message)
					sendMessagePush('[图片]')
					toDown(500)
				}, {
					to: conversationId.value
				})
				break;
			case 'video':
				imServer.value.sendVideo((res) => {
					popupRef.value.close()
					chatList.value.push(res.message)
					sendMessagePush('[视频]')
					toDown(500)
				}, {
					to: conversationId.value
				})
				break;
		}
	}
	
	const sendMessagePush = async (content)=>{
		const res : any = await api({
			method: 'post',
			url: `/mall/user/sendMessagePush`,
			data:{
				"userId":userInfo.value.id,
				"avatar":userInfo.value.avatar,
				"username":userInfo.value.nickName,
				"content":content,
				"receiveUserId":userfromInfo.value.id
			}
		})
	}
</script>

<style lang="scss" scoped>
	.content {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		height: 100vh;
		.scroll {
			height: calc(100vh - calc(20rpx + 90rpx + var(--safe-area-bottom) + 20rpx));

			.show-time {
				color: #7C807F;
				text-align: center;
				font-size: 26rpx;
				padding-top: 10rpx;
			}
		}

		.send {
			background-color: #fff;
			width: 100%;
			padding: 20rpx 32rpx calc(var(--safe-area-bottom) + 20rpx);
			box-sizing: border-box;

			.send-content {
				display: flex;
				align-items: center;
				justify-content: space-between;

				>image {
					width: 48rpx;
					height: 48rpx;
					flex-shrink: 0;
				}

				.text-input {
					background-color: var(--pages-bg-color);
					border-radius: 50rpx;
					height: 80rpx;
					padding: 0 40rpx;
					font-size: 28rpx;
					border: 1px solid #FFA3A3;
					flex: 1;
					margin: 0 28rpx;
				}

				.btn {
					height: 76rpx;
					width: 154rpx;
					flex-shrink: 0;
				}
			}
		}

	}

	.pop {
		background-color: #fff;
		padding: 12rpx 32rpx;

		.line {
			text-align: center;
			font-size: 32rpx;
			padding: 32rpx 0;
			border-bottom: 1rpx solid var(--pages-bg-color);
		}

		.line:last-child {
			border-bottom: 0;
		}
	}

	.videoImgPop {
		width: 100vw;
		height: 100vh;
		background-color: #000;
		position: relative;

		.close {
			position: absolute;
			right: 40rpx;
			top: 40rpx;
		}

		>video {
			width: 100%;
			height: 45vh;
			margin-top: 27.5vh;
		}

		.image-content {
			width: 100vw;
			height: 100vh;
			display: flex;
			justify-content: center;
			overflow-y: scroll;

			>image {
				width: 100%;
			}
		}

	}
</style>